import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:dartz/dartz.dart';

import '../core/api_result.dart';
import '../core/base_repository.dart';
import '../core/http_client.dart';
import '../../models/auth_models.dart';

/// 认证Repository
class AuthRepository extends BaseRepository {
  AuthRepository(super.httpClient);

  /// 发送验证码
  Future<ApiResult<SendCodeResponse>> sendVerificationCode(String phoneNumber) async {
    final request = SendCodeRequest(phoneNumber: phoneNumber);
    final path = '/auth/send-code';
    
    try {
      final result = await post<SendCodeResponse>(
        path,
        data: request.toJson(),
        fromJson: SendCodeResponse.fromJson,
      );
      
      // 如果请求失败，在错误信息中添加完整URL
      if (result.isLeft()) {
        final baseUrl = httpClient.baseUrl;
        final fullUrl = '$baseUrl$path';
        final failure = result.fold((l) => l, (r) => null)!;
        final originalError = failure.message;
        return Left(ServerFailure('发送验证码失败 [URL: $fullUrl]: $originalError'));
      }
      
      return result;
    } catch (e) {
      final baseUrl = httpClient.baseUrl;
      final fullUrl = '$baseUrl$path';
      return Left(ServerFailure('发送验证码失败 [URL: $fullUrl]: $e'));
    }
  }

  /// 验证码登录
  Future<ApiResult<LoginResponse>> verifyCodeAndLogin({
    required String phoneNumber,
    required String code,
    required String verificationId,
  }) async {
    final request = VerifyCodeRequest(
      phoneNumber: phoneNumber,
      code: code,
      verificationId: verificationId,
    );
    return post<LoginResponse>(
      '/auth/verify-code',
      data: request.toJson(),
      fromJson: LoginResponse.fromJson,
    );
  }

  /// 刷新Token
  Future<ApiResult<LoginResponse>> refreshToken(String refreshToken) async {
    final request = RefreshTokenRequest(refreshToken: refreshToken);
    return post<LoginResponse>(
      '/auth/refresh-token',
      data: request.toJson(),
      fromJson: LoginResponse.fromJson,
    );
  }

  /// 验证Token
  Future<ApiResult<UserInfo>> validateToken() async {
    return get<UserInfo>(
      '/auth/validate-token',
      fromJson: UserInfo.fromJson,
    );
  }

  /// 获取用户信息
  Future<ApiResult<UserInfo>> getUserInfo() async {
    return get<UserInfo>(
      '/auth/user-info',
      fromJson: UserInfo.fromJson,
    );
  }

  /// 登出
  Future<ApiResult<void>> logout() async {
    return post<void>('/auth/logout');
  }
}

/// AuthRepository Provider - 使用响应式HTTP客户端
final authRepositoryProvider = Provider<AuthRepository>(
  (ref) => AuthRepository(ref.watch(reactiveHttpClientProvider)),
);

